package edu.zcmu.seckill.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import edu.zcmu.seckill.entity.*;
import edu.zcmu.seckill.exception.MyException;
import edu.zcmu.seckill.mapper.AdminMapper;
import edu.zcmu.seckill.response.R;
import edu.zcmu.seckill.response.ResultCode;
import edu.zcmu.seckill.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.zcmu.seckill.service.ProductService;
import edu.zcmu.seckill.service.SeckillProductPolicyService;
import edu.zcmu.seckill.service.SeckillProductService;
import edu.zcmu.seckill.utils.JwtUtil;
import edu.zcmu.seckill.vo.AddFromVo;
import edu.zcmu.seckill.vo.AdminLoginVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 唐诗
 * @since 2022-04-16
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    SeckillProductPolicyService seckillProductPolicyService;
    @Autowired
    SeckillProductService seckillProductService;
    @Autowired
    ProductService productService;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Override
    public R login(AdminLoginVo loginVo) {
        String name = loginVo.getName();
        String password = loginVo.getPassword();
        if (StringUtils.isEmpty(name)||StringUtils.isEmpty(password)){
            throw new MyException(ResultCode.ERROR,"填写项不允许为空");
        }

        Admin admin = baseMapper.selectOne(new QueryWrapper<Admin>().eq("name", name));
        if (ObjectUtils.isEmpty(admin)){
            throw new MyException(ResultCode.ERROR,"用户不存在");
        }
        if(!new BCryptPasswordEncoder().matches(password, admin.getPassword())){
            throw new MyException(ResultCode.ERROR,"账号或密码错误");
        }

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name",loginVo.getName());
        String token = jwtUtil.createToken(hashMap);
        return R.ok().data("atoken",token);
    }

    @Override
    public R getSeckillProduct(HttpServletRequest request) {
        //获取用户token
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(request.getHeader("atoken"));
        String name = tokenInfo.getClaim("name").asString();
        if (StringUtils.isEmpty(name)){
            throw new MyException(ResultCode.ERROR,"管理员信息异常");
        }
        BaseMapper<SeckillProduct> baseMapper = seckillProductService.getBaseMapper();
        List<SeckillProduct> seckillProducts = baseMapper.selectList(null);
        return R.ok().data("data",seckillProducts);
    }

    @Override
    public R getNormalProduct(HttpServletRequest request) {
        //获取用户token
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(request.getHeader("atoken"));
        String name = tokenInfo.getClaim("name").asString();
        if (StringUtils.isEmpty(name)){
            throw new MyException(ResultCode.ERROR,"管理员信息异常");
        }
        BaseMapper<Product> baseMapper = productService.getBaseMapper();
        List<Product> list = baseMapper.selectList(null);
        return R.ok().data("data",list);
    }

    @Override
    @Transactional
    public R addSeckillProduct(AddFromVo addFromVo, HttpServletRequest request) {
        //获取用户token
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(request.getHeader("atoken"));
        String name = tokenInfo.getClaim("name").asString();
        if (StringUtils.isEmpty(name)){
            throw new MyException(ResultCode.ERROR,"管理员信息异常");
        }
        SeckillProduct product = new SeckillProduct();
        BeanUtils.copyProperties(addFromVo,product);
        product.setSale(0);
        seckillProductService.getBaseMapper().insert(product);
        SeckillProductPolicy seckillProductPolicy = new SeckillProductPolicy();
        if ("是".equals(addFromVo.getJob())){
            seckillProductPolicy.setJob(0);
        }else{
            seckillProductPolicy.setJob(1);
        }
        if ("是".equals(addFromVo.getDishonesty())){
            seckillProductPolicy.setDishonesty(0);
        }else{
            seckillProductPolicy.setDishonesty(1);
        }
        if ("是".equals(addFromVo.getOverdue())){
            seckillProductPolicy.setOverdue(0);
        }else{
            seckillProductPolicy.setOverdue(1);
        }
        seckillProductPolicy.setId(product.getId());
        seckillProductPolicyService.getBaseMapper().insert(seckillProductPolicy);
        if (Boolean.TRUE.equals(addFromVo.getIs())){
            //跟新缓存
            threadPoolExecutor.execute(()->{
                seckillProductService.uploadSeckillProductCache();
            });
        }
        return R.ok();
    }

    @Override
    public R delSeckillProduct(int id,HttpServletRequest request) {
        //获取用户token
        DecodedJWT tokenInfo = JwtUtil.getTokenInfo(request.getHeader("atoken"));
        String name = tokenInfo.getClaim("name").asString();
        if (StringUtils.isEmpty(name)){
            throw new MyException(ResultCode.ERROR,"管理员信息异常");
        }
        BaseMapper<SeckillProduct> baseMapper = seckillProductService.getBaseMapper();
        baseMapper.deleteById(id);
        seckillProductPolicyService.getBaseMapper().deleteById(id);
        return R.ok();
    }


}
